from sqlmodel import Session, select
from ..models.permission import (
    User,Role,Permission,
    Menu,UserRole,RolePermission,MenuPermission
)
from ..schemas.permission import (
    UserCreate,RoleCreate,PermissionCreate,MenuCreate
)

# ===================== 用户相关的CRUD =======================
def get_user(session: Session, user_id: int):
    return session.get(User, user_id)

def get_user_by_username(session: Session, username: str):
    return session.exec(select(User).where(User.username == username)).first()

def create_user(session: Session, user_create: UserCreate):
    db_user = User(
        username=user_create.username,
        email=user_create.email,
        full_name=user_create.full_name,
        is_superuser=user_create.is_superuser,
        is_active=user_create.is_active
    )
    db_user.set_password(user_create.password)
    session.add(db_user)
    session.commit()
    session.refresh(db_user)
    return db_user


# ======================= 角色相关的CRUD ======================
def get_role(session: Session, role_id: int):
    return session.get(Role, role_id)

def get_role_by_code(session:Session, code:str):
    return session.exec(select(Role).where(Role.code == code)).first()

def create_role(session:Session, role_create: RoleCreate):
    db_role = Role(
        name = role_create.name,
        code = role_create.code,
        description = role_create.description,
        is_active = role_create.is_active
    )
    session.add(db_role)
    session.commit()
    session.refresh(db_role)
    return db_role

# ===================== 权限相关的CRUD ============================
def get_permission(session: Session, permission_id: int):
    return session.get(Permission, permission_id)

def get_permission_by_code(session: Session, code: str):
    return session.exec(select(Permission).where(Permission.code == code)).first()

def create_permission(session: Session, permission_create: PermissionCreate):
    db_permission = Permission(
        name=permission_create.name,
        code=permission_create.code,
        description=permission_create.description,
        resource_type=permission_create.resource_type
    )
    session.add(db_permission)
    session.commit()
    session.refresh(db_permission)
    return db_permission

# ====================== 菜单相关的CRUD ==========================
def get_menu(session: Session, menu_id: int):
    return session.get(Menu, menu_id)

def get_menu_tree(session: Session):
    """获取菜单树"""
    # 获取顶级菜单
    top_menus = session.exec(
        select(Menu).where(Menu.parent_id.is_(None), Menu.is_active == True)
        .order_by(Menu.order)
    ).all()

    def build_menu_tree(menu: Menu):
        """递归构建菜单树"""
        children = session.exec(
            select(Menu)
            .where(Menu.parent_id == menu.id, Menu.is_active == True)
            .order_by(Menu.order)
        ).all()
        menu.children = [build_menu_tree(child) for child in children]
        return  menu

    return [build_menu_tree(top_menu) for top_menu in top_menus]

def get_user_menus_by_permission_codes(session: Session, permission_codes: list[str]):
    user_menu_codes = session.exec(
        select(Menu)
        .join(MenuPermission)
        .join(Permission)
        .where(Permission.code.in_(permission_codes))
    ).all()
    return user_menu_codes

def create_menu(session:Session, menu_create: MenuCreate):
    db_menu = Menu(
        name=menu_create.name,
        path=menu_create.path,
        icon=menu_create.icon,
        order=menu_create.order,
        parent_id=menu_create.parent_id,
        component=menu_create.component,
        is_active=menu_create.is_active,
    )
    session.add(db_menu)
    session.commit()
    session.refresh(db_menu)
    return db_menu

